package com.atguigu.gmall.order.listener;

import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.mq.config.component.RabbitService;
import com.atguigu.gmall.mq.ware.WareDeductMsg;
import com.atguigu.gmall.order.biz.OrderBizService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Author:lyd
 * @Date:2023/9/7 14:48
 * @Version:1.0
 * @Description
 **/
@Service
@Slf4j
public class OrderDeductListener {

    @Autowired
    OrderBizService orderBizService;

    @Autowired
    RabbitService rabbitService;

    //绑定队列和交换机
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(name = "queue.ware.order",
                            durable = "true",
                            exclusive = "false",
                            autoDelete = "false"),
                    exchange = @Exchange(name = "exchange.direct.ware.order",
                            type = "topic",
                            durable = "true",
                            autoDelete = "false"),
                    key = "ware.order"
            )})
    public void handle(Message message, Channel channel) throws IOException {
        String json = new String(message.getBody());
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            //1、获取消息
            WareDeductMsg msg = JSONs.jsonToObj(json, WareDeductMsg.class);
            //2、处理业务，订单状态修改
            orderBizService.deductStatusOrder(msg);
            //3、处理成功，手动恢复欧克
            channel.basicAck(deliveryTag,false);
        } catch (Exception e) {
            //4、处理失败，重试
            log.info("修改订单状态失败：{}", e.getMessage());
            rabbitService.reTry(json, channel, deliveryTag, 5);
        }
    }

}